<template>
  <!-- 我的预约（家长或教员） -->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约状态">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 140px;">
          <el-option label="全部" value="" />
          <el-option
            v-for="item in dict.type.order_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['appointment:appointment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['appointment:appointment:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          v-if="isParent||isAdmin"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['appointment:appointment:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['appointment:appointment:export']"
        >导出</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getListByParentName"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="appointmentList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="appointmentId" sortable="custom" :sort-by="['appointmentId']"/>
      <el-table-column label="家长姓名" align="center" prop="parentName" />
      <el-table-column label="家长电话" align="center" prop="phoneNumber" />
      <el-table-column label="教师姓名" align="center" prop="teacherName" />
      <el-table-column label="预约说明" align="center" prop="detail">
        <template slot-scope="scope">
          <div 
            @click="showDetailDialog(scope.row.detail)" 
            style="cursor: pointer; max-width: 200px;"
          >
            {{ scope.row.detail ? 
              (scope.row.detail.length > 20 ? 
                scope.row.detail.substring(0, 20) + '...' : 
                scope.row.detail) 
              : '-' }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="isParent && scope.row.status === 'pending'||isAdmin"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['appointment:appointment:edit']"
          >修改</el-button>
          <el-button
            v-if="isParent && scope.row.status === 'pending'||isAdmin" 
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['appointment:appointment:remove']"
          >删除</el-button>
          <el-button
            v-if="isTeacher && scope.row.status === 'pending'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleConfirm(scope.row)"
            v-hasPermi="['appointment:appointment:edit']"
          >确认预约</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handlePagination"
    />

    <!-- 添加或修改我的预约对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="家长电话" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入家长电话" />
        </el-form-item>
        <!-- <el-form-item label="教师姓名" prop="teacherName">
          <el-input v-model="form.teacherName" placeholder="请输入教师姓名" />
        </el-form-item> -->
        <el-form-item label="预约说明" prop="detail">
          <el-input v-model="form.detail" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="预约状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.order_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 预约说明详情对话框 -->
    <el-dialog 
      title="预约说明" 
      :visible.sync="detailDialogVisible" 
      width="50%"
      :modal="true"
    >
      <div style="white-space: pre-wrap; max-height: 60vh; overflow-y: auto;">
        {{ currentDetail }}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { listAppointment, getAppointment, delAppointment, addAppointment, updateAppointment, getListByParentName, getListByTeacherName, confirmAppointment } from "@/api/appointment/appointment";

export default {
  name: "Appointment",
  dicts: ['order_status'],
  computed: {
    isParent() {
      return localStorage.getItem("roleName") === "家长";
    },
    isTeacher() {
      return localStorage.getItem("roleName") === "教员";
    },
    isAdmin(){
      return localStorage.getItem("roleName") === "超级管理员";
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 我的预约表格数据
      appointmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 预约说明详情对话框
      detailDialogVisible: false,
      currentDetail: '',
    };
  },
  created() {
    if (this.$route.query.parentName!=null) {
      // 家长查看自己的预约
      this.getListByParentName();
    } else if
      (this.$route.query.teacherName != null)
    {
      // 教员查看自己的预约
      this.getListByTeacherName();
    }
    else {
      // 管理员查看所有预约
      this.listAppointment();
      // console.log('666666666666666');
    
    }
  },
  methods: {
    handlePagination(pagination) {
      this.queryParams.pageNum = pagination.page;
      this.queryParams.pageSize = pagination.limit;
      this.handleQuery(); // 复用现有的查询方法
    },
    // 管理员查看所有预约
    listAppointment(){
      this.loading = true;
      listAppointment(this.queryParams).then(response => {
        this.appointmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 根据教员姓名查询预约列表
    getListByTeacherName(){
      this.loading = true;
      getListByTeacherName(this.$route.query.teacherName,this.queryParams.status).then(response => {
        this.appointmentList = response;
        this.loading = false;
      });
    },
    // 根据家长姓名查询预约列表
    getListByParentName() {
      this.loading = true;
      getListByParentName(this.$route.query.parentName,this.queryParams.status).then(response => {
        this.appointmentList = response;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        appointmentId: null,
        parentName: null,
        phoneNumber: null,
        teacherName: null,
        detail: null,
        startTime: null,
        endTime: null,
        status: null
      };
      this.resetForm("form");
    },
    showDetailDialog(detail) {
    this.currentDetail = detail || '暂无说明';
    this.detailDialogVisible = true;
  },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.$route.query.parentName!=null) {
        this.getListByParentName();
      } else if (this.$route.query.teacherName != null) {
        this.getListByTeacherName();
      } else {
        this.listAppointment();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.status = '';
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.appointmentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加我的预约";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const appointmentId = row.appointmentId || this.ids
      getAppointment(appointmentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改我的预约";
      });
    },
    /** 确认预约按钮操作 */
    handleConfirm(row) {
      this.$modal.confirm('是否确认该预约？').then(() => {
        confirmAppointment(row.appointmentId).then(response => {
          this.$modal.msgSuccess("确认成功");
          if (this.isParent) {
            this.getListByParentName();
          } else {
            this.getListByTeacherName();
          }
        });
      }).catch(() => {});
    },
    // 处理排序事件
    handleSortChange({ column, prop, order }) {
      if (prop === 'appointmentId') {
        // 对 appointmentList 进行排序
        this.appointmentList.sort((a, b) => {
          const idA = Number(a.appointmentId);
          const idB = Number(b.appointmentId);
          if (order === 'ascending') {
            return idA - idB; // 升序
          } else {
            return idB - idA; // 降序
          }
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.appointmentId != null) {
            updateAppointment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              if (this.isParent) {
                this.getListByParentName();
              } else {
                this.getListByTeacherName();
              }
            });
          } else {
            this.form.parentName = localStorage.getItem("userName");
            this.form.phoneNumber = localStorage.getItem("parentPhoneNumber");
            this.form.status = "pending";
            addAppointment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              if (this.isParent) {
                this.getListByParentName();
              } else {
                this.getListByTeacherName();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const appointmentIds = row.appointmentId || this.ids;
      this.$modal.confirm('是否确认删除我的预约编号为"' + appointmentIds + '"的数据项？').then(function() {
        return delAppointment(appointmentIds);
      }).then(() => {
        if (this.isParent) {
          this.getListByParentName();
        } else {
          this.getListByTeacherName();
        }
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('appointment/appointment/export', {
        ...this.queryParams
      }, `appointment_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 30px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f6f8fc 0%, #f1f4f9 100%);
}

.app-container .el-form {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  padding: 25px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.8);
  margin-bottom: 25px;
}

.app-container .el-form .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
}

.app-container .el-form .el-form-item .el-input__inner,
.app-container .el-form .el-form-item .el-select .el-input__inner {
  border-radius: 8px;
  border-color: #dcdfe6;
  transition: all 0.3s ease;
}

.app-container .el-form .el-form-item .el-input__inner:hover,
.app-container .el-form .el-form-item .el-input__inner:focus,
.app-container .el-form .el-form-item .el-select .el-input__inner:hover,
.app-container .el-form .el-form-item .el-select .el-input__inner:focus {
  border-color: #e61e1e;
}

.app-container .el-form .el-form-item .el-button {
  padding: 8px 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.app-container .el-form .el-form-item .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.app-container .mb8 {
  margin-bottom: 25px;
}

.app-container .mb8 .el-button {
  padding: 10px 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.app-container .mb8 .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.app-container .mb8 .el-button.el-button--primary {
  background: linear-gradient(135deg, #e61e1e, #ff6b6b);
  border: none;
}

.app-container .mb8 .el-button.el-button--primary:hover {
  background: linear-gradient(135deg, #ff6b6b, #e61e1e);
}

.app-container .el-table {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.8);
  margin-bottom: 25px;
}

.app-container .el-table::before {
  display: none;
}

.app-container .el-table .el-table__header-wrapper th {
  background: rgba(230, 30, 30, 0.05);
  color: #2c3e50;
  font-weight: 600;
  padding: 15px 0;
}

.app-container .el-table .el-table__body-wrapper td {
  padding: 15px 0;
  color: #606266;
}

.app-container .el-table .el-button {
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.app-container .el-table .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.app-container .el-table .el-button.el-button--danger {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
  border: none;
}

.app-container .el-table .el-button.el-button--danger:hover {
  background: linear-gradient(135deg, #ff7875, #ff4d4f);
}

.app-container .el-pagination {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  padding: 20px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.8);
  text-align: center;
}

.app-container .el-pagination .el-pagination__total,
.app-container .el-pagination .el-pagination__jump {
  color: #606266;
}

.app-container .el-pagination .btn-prev,
.app-container .el-pagination .btn-next,
.app-container .el-pagination .el-pager li {
  background: transparent;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.app-container .el-pagination .btn-prev:hover,
.app-container .el-pagination .btn-next:hover,
.app-container .el-pagination .el-pager li:hover {
  color: #e61e1e;
  border-color: #e61e1e;
}

.app-container .el-pagination .btn-prev.active,
.app-container .el-pagination .btn-next.active,
.app-container .el-pagination .el-pager li.active {
  background: #e61e1e;
  color: white;
  border-color: #e61e1e;
}

.app-container .el-dialog {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.app-container .el-dialog .el-dialog__header {
  background: linear-gradient(135deg, #e61e1e, #ff6b6b);
  padding: 20px;
  margin: 0;
}

.app-container .el-dialog .el-dialog__header .el-dialog__title {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.app-container .el-dialog .el-dialog__header .el-dialog__headerbtn {
  top: 20px;
}

.app-container .el-dialog .el-dialog__header .el-dialog__headerbtn .el-icon-close {
  color: white;
}

.app-container .el-dialog .el-dialog__body {
  padding: 30px;
}

.app-container .el-dialog .el-dialog__body .el-form-item__label {
  font-weight: 500;
  color: #2c3e50;
}

.app-container .el-dialog .el-dialog__body .el-input__inner,
.app-container .el-dialog .el-dialog__body .el-textarea__inner {
  border-radius: 8px;
  border-color: #dcdfe6;
  transition: all 0.3s ease;
}

.app-container .el-dialog .el-dialog__body .el-input__inner:hover,
.app-container .el-dialog .el-dialog__body .el-input__inner:focus,
.app-container .el-dialog .el-dialog__body .el-textarea__inner:hover,
.app-container .el-dialog .el-dialog__body .el-textarea__inner:focus {
  border-color: #e61e1e;
}

.app-container .el-dialog .el-dialog__footer {
  padding: 20px 30px;
  border-top: 1px solid #ebeef5;
}

.app-container .el-dialog .el-dialog__footer .el-button {
  padding: 10px 25px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.app-container .el-dialog .el-dialog__footer .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

@media screen and (max-width: 768px) {
  .app-container {
    padding: 20px;
  }

  .app-container .el-form {
    padding: 15px;
  }

  .app-container .el-form .el-form-item {
    margin-right: 10px;
  }

  .app-container .el-table .el-table__header-wrapper th,
  .app-container .el-table .el-table__body-wrapper td {
    padding: 10px 0;
  }
}
</style>
